package com.gxitsky.common.rsa;

import com.gxitsky.common.utils.RSAUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;

import java.io.File;

/**
 * @author gxing
 * @desc TODO
 * @date 2021/12/28
 */
public class ClassFileRSATest {

    public static void main(String[] args) throws Exception {
        RSAUtil.RSAKeyPair rsaKeyPair = RSAUtil.genKeyPair();
        String classFile = "D:/People.class";
//        String content = rsaEncrypt(classFile, rsaKeyPair.getPublicKey());
//        rsaDecrypt(content, rsaKeyPair.getPrivateKey());
        rsaEncrypt(classFile, rsaKeyPair.getPublicKey());
        rsaDecrypt(rsaKeyPair.getPrivateKey());
    }

    /**
     * @param path      文件路径
     * @param publicKey 公钥
     * @desc 加密
     * @author gxing
     * @date 2021/12/29 9:31
     */
    public static String rsaEncrypt(String path, String publicKey) throws Exception {
        File file = new File(path);
        byte[] bytes = FileUtils.readFileToByteArray(file);
        byte[] encrypt = RSAUtil.encrypt(bytes, publicKey);
        File people = new File("D:/clazz/People.clazz");
        FileUtils.writeByteArrayToFile(people, encrypt);
        return Base64.encodeBase64String(encrypt);
    }

    /**
     * @param content    文件路径
     * @param privateKey 私钥
     * @desc 加密
     * @author gxing
     * @date 2021/12/29 9:31
     */
    public static void rsaDecrypt(String content, String privateKey) throws Exception {
        byte[] bytes = Base64.decodeBase64(content);
        byte[] decrypt = RSAUtil.decrypt(bytes, privateKey);
        File people = new File("D:/clazz/People.class");
        FileUtils.writeByteArrayToFile(people, decrypt);
    }

    /**
     * @param privateKey 私钥
     * @desc 加密
     * @author gxing
     * @date 2021/12/29 9:31
     */
    public static void rsaDecrypt(String privateKey) throws Exception {
        File people = new File("D:/clazz/People.clazz");
        byte[] bytes = FileUtils.readFileToByteArray(people);
        byte[] decrypt = RSAUtil.decrypt(bytes, privateKey);
        File peopleClass = new File("D:/clazz/People.class");
        FileUtils.writeByteArrayToFile(peopleClass, decrypt);
    }
}




